package com.example.homework

import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.example.homework.db.UserDBHelper
import com.example.homework.utils.Prefs
import com.example.homework.utils.RankUtils
import com.google.android.material.button.MaterialButton
import com.yalantis.ucrop.UCrop
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import kotlinx.coroutines.*

class ProfileEditActivity : AppCompatActivity() {

    private lateinit var ivAvatar: ImageView
    private lateinit var etNickname: EditText
    private lateinit var btnCamera: MaterialButton
    private lateinit var btnGallery: MaterialButton
    private lateinit var btnSave: MaterialButton

    private var newAvatarUri: Uri? = null   // 最终裁剪结果

    private val cropLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // 官方 API 取裁剪后的 Uri
                val cropped = UCrop.getOutput(result.data!!)
                if (cropped != null) {
                    newAvatarUri = cropped
                    ivAvatar.setImageURI(cropped)
                } else {
                    Toast.makeText(this, "裁剪失败", Toast.LENGTH_SHORT).show()
                }
            } else if (result.resultCode == UCrop.RESULT_ERROR) {
                val throwable = UCrop.getError(result.data!!)
                Toast.makeText(this, "裁剪出错: ${throwable?.message}", Toast.LENGTH_SHORT).show()
            }
        }

    private val cameraLauncher =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
            if (success) {
                newAvatarUri?.let { gotoCrop(it) }
            } else {
                Toast.makeText(this, "拍照失败", Toast.LENGTH_SHORT).show()
            }
        }

    private val galleryLauncher =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
            uri?.let { gotoCrop(it) }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_profile_edit)

        ivAvatar = findViewById(R.id.iv_avatar_edit)
        etNickname = findViewById(R.id.et_nickname)
        btnCamera  = findViewById(R.id.btn_camera)
        btnGallery = findViewById(R.id.btn_gallery)
        btnSave    = findViewById(R.id.btn_save)

        loadOldData()

        btnCamera.setOnClickListener  { openCamera() }
        btnGallery.setOnClickListener { openGallery() }
        btnSave.setOnClickListener    { saveAndExit() }
    }

    private fun loadOldData() {
        val account = Prefs.lastAccount(this) ?: return
        UserDBHelper(this).use { db ->
            val user = db.getUserByAccount(account) ?: return
            etNickname.setText(user.username)
            if (user.avatar.isNotEmpty()) {
                ivAvatar.setImageURI(Uri.parse(user.avatar))
            }
        }
    }

    private fun openCamera() {
        val file = File(cacheDir, "temp_${System.currentTimeMillis()}.jpg")
        newAvatarUri = FileProvider.getUriForFile(this, "$packageName.provider", file)
        cameraLauncher.launch(newAvatarUri!!)
    }

    private fun openGallery() {
        galleryLauncher.launch("image/*")
    }

    private fun gotoCrop(src: Uri) {
        val time = System.currentTimeMillis()
        val destFile = File(cacheDir, "cropped_$time.jpg")
        val destUri = Uri.fromFile(destFile)

        val options = UCrop.Options().apply {
            setFreeStyleCropEnabled(true)          // 自由框选
            setCompressionFormat(Bitmap.CompressFormat.JPEG)
            setCompressionQuality(90)
            // 关键：让 UCrop 使用我们在 manifest 里注册的 authority
            // 库会自动用该 authority 生成 content:// URI
        }

        val uCrop = UCrop.of(src, destUri)
            .withOptions(options)
            .withAspectRatio(1f, 1f)
            .withMaxResultSize(300, 300)

        cropLauncher.launch(uCrop.getIntent(this))
    }

    private fun saveAndExit() {
        val nick = etNickname.text.toString().trim()
        if (nick.isEmpty()) {
            Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        val account = Prefs.lastAccount(this) ?: return

        CoroutineScope(Dispatchers.IO).launch {
            UserDBHelper(this@ProfileEditActivity).use { db ->
                db.updateUsername(account, nick)
                newAvatarUri?.let {
                    db.updateAvatar(account, it.toString())

                    // 上传头像到服务器
                    val imageUrl = RankUtils.uploadImage(this@ProfileEditActivity, it)
                    if (imageUrl != null) {
                        // 更新数据库中的头像路径为服务器返回的URL
                        db.updateAvatar(account, imageUrl)
                        withContext(Dispatchers.Main) {
                            Toast.makeText(this@ProfileEditActivity, "头像已上传到服务器", Toast.LENGTH_SHORT).show()
                        }
                    } else {
                        withContext(Dispatchers.Main) {
                            Toast.makeText(this@ProfileEditActivity, "头像上传失败，请检查网络", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            }

            // 获取更新后的用户信息
            val updatedUser = UserDBHelper(this@ProfileEditActivity).getUserByAccount(account) ?: return@launch

            // 更新服务器端用户信息
            val updated = RankUtils.updateUser(updatedUser, this@ProfileEditActivity)
            if (updated) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@ProfileEditActivity, "用户信息已同步到服务器", Toast.LENGTH_SHORT).show()
                }
            } else {
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@ProfileEditActivity, "用户信息同步失败，请检查网络", Toast.LENGTH_SHORT).show()
                }
            }

            withContext(Dispatchers.Main) {
                setResult(RESULT_OK)
                finish()
            }
        }
    }
}